﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Jermaine.UI;

namespace AutoUpdater
{
    public partial class UpdatingForm : Form
    {
        #region 字段
        private PackageInfo packageInfo;
        private string externalApp;
        private Notify notify;
        private static readonly String Tmpdir = System.Environment.GetEnvironmentVariable("TMP");
        private static readonly String Notification = Resource.GetString("UpdatingForm.Notification");
        private DownloadControl downLoadControl;
        #endregion

        #region 构造器
        public UpdatingForm(PackageInfo packageInfo, string externalApp)
            : this() {
            this.packageInfo = packageInfo;
            this.externalApp = externalApp;
            this.Load += UpdatingFormLoad;
        }

        public UpdatingForm() {
            this.notify = new Notify(this) { Visible = false };
            this.Controls.Add(notify);
            this.StartPosition = FormStartPosition.CenterScreen;
            InitializeComponent();
            this.Text = Resource.GetString("UpdatingForm.Title");
        }
        #endregion

        #region 事件方法

        private void UpdatingFormLoad(object sender, EventArgs e) {
            this.Hide();
            if (this.packageInfo.Files.Count() == 0) {
                this.Dispose(true);
            } else {
                this.downLoadControl = new DownloadControl(packageInfo.Files);
                downLoadControl.DownloadCompleted += DownloadCompleted;
                downLoadControl.ProgressUpdating += ProgressUpdating;
                downLoadControl.StartDownloading += StartDownloading;
                this.Controls.Add(downLoadControl);
                downLoadControl.StartDownload();
            }
        }

        /// <summary>
        /// 开始下载事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StartDownloading(object sender, EventArgs e) {
            this.Show();
        }


        /// <summary>
        /// 完成事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DownloadCompleted(object sender, EventArgs e) {
            this.StartInstaller();
            UIInvoker.AsyncCall(this, () => {

                this.Visible = false;
                this.notify.Visible = false;
                this.Controls.Remove(downLoadControl);
                this.downLoadControl.Dispose();
            });

        }

        /// <summary>
        /// 更新进度
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ProgressUpdating(object sender, DownloadControl.ProgressUpdatingEventArgs e) {
            UIInvoker.AsyncCall(this, () => {
                var text = string.Format(Notification, e.Percent, e.Rate);
                this.notify.Notification = text;
            });
        }


        /// <summary>
        /// 进程退出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Exited(object sender, EventArgs e) {
            UIInvoker.AsyncCall(this, () => {
                this.notify.Dispose();
                this.Dispose(true);
            });
            Environment.Exit(0);
        }
        #endregion

        #region 方法
        protected override void OnFormClosing(FormClosingEventArgs e) {

            e.Cancel = true;
            this.notify.Visible = true;
            this.Hide();
            base.OnFormClosing(e);
        }



        /// <summary>
        /// 获取安装包路径
        /// </summary>
        /// <returns></returns>
        private String GetInstaller() {
            var path = Path.Combine(Tmpdir, "AutoUpdater");
            if (!Directory.Exists(path)) {
                return string.Empty;
            }
            foreach (var item in new DirectoryInfo(path).GetFiles()) {
                if (item.Name.ToUpper() == this.packageInfo.Installer.ToUpper()) {
                    return item.FullName;
                }
            }
            return string.Empty;
        }

        /// <summary>
        /// 干掉进程
        /// </summary>
        private void KillExternalApp() {
            foreach (var item in Process.GetProcesses().Where(
                o => o.ProcessName.ToUpper().Contains(this.externalApp.ToUpper()))) {
                item.Kill();
            }

        }

        /// <summary>
        /// 启动安装包
        /// </summary>
        private void StartInstaller() {
            this.KillExternalApp();
            var installer = GetInstaller();

            if (!File.Exists(installer) || string.IsNullOrEmpty(installer)) {
                UIInvoker.AsyncCall(this, () => {
                    this.notify.Dispose();
                    this.Dispose(true);
                });
                Environment.Exit(0);
            }

            var process = Process.Start(new ProcessStartInfo {
                FileName = installer
            });
            process.EnableRaisingEvents = true;
            process.Exited += Exited;
        }

        #endregion
    }
}
